package com.sneakxy.mybase4j.generator;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;

import com.sneakxy.mybase4j.generator.config.Dirs;

/**
 * @author 潜行的青衣
 * @see
 */
@Mojo(name = "run", requiresDependencyResolution = ResolutionScope.COMPILE)
public class GeneratorMavenPlugin extends AbstractMojo {

	@Parameter(defaultValue = "src/main/resources/generator-config.xml", required = true)
	private String configPath;

	@Parameter(defaultValue = "${basedir}", required = true)
	private String basedir;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.maven.plugin.Mojo#execute()
	 */
	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		this.initDirAndPath();
		try {
			Generator generator = new Generator(new StringBuilder().append(basedir).append(configPath).toString());
			Dirs dirs = generator.getConfig().getDirs();
			// 处理路径
			dirs.setOutDir(fullDir(dirs.getOutDir()));
			dirs.setModelOutDir(fullDir(dirs.getModelOutDir()));
			dirs.setRepositoryOutDir(fullDir(dirs.getRepositoryOutDir()));
			dirs.setServiceInterfaceOutDir(fullDir(dirs.getServiceInterfaceOutDir()));
			dirs.setServiceImplOutDir(fullDir(dirs.getServiceImplOutDir()));
			generator.start();
		} catch (FileNotFoundException e) {
			throw new MojoExecutionException("代码生成失败.", e);
		} catch (IOException e) {
			throw new MojoExecutionException("代码生成失败.", e);
		}
	}

	private void initDirAndPath() {
		basedir = formatDir(basedir);
		if (!StringUtils.endsWith(basedir, File.separator)) {
			basedir = new StringBuilder().append(basedir).append(File.separator).toString();
		}
		configPath = formatDir(configPath);
	}

	private String formatDir(String dir) {
		if (StringUtils.isBlank(dir)) {
			return null;
		}
		String result = StringUtils.replace(dir, "/", File.separator);
		return StringUtils.replace(result, "\\", File.separator);
	}

	private String fullDir(String dir) {
		String result = formatDir(dir);
		if (StringUtils.isBlank(dir))
			return null;
		if (StringUtils.indexOf(result, ":") < 0 && !StringUtils.startsWith(result, File.separator)) {
			result = new StringBuilder().append(basedir).append(result).toString();
		}
		return result;
	}

}
